package com.sychip.fhc.app.todo

//import no.nordicsemi.android.common.permissions.ble.RequireBluetooth
//import no.nordicsemi.android.common.permissions.ble.RequireLocation
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.DragIndicator
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Subtitles
import androidx.compose.material.icons.filled.SubtitlesOff
import androidx.compose.material.icons.filled.Tab
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.fhc.connectivity.ConnectionState
import com.fhc.connectivity.NetworkViewModel
import com.sychip.fhc.APP
import com.sychip.fhc.AppType
import com.sychip.fhc.app.accontrol.AcControl
import com.sychip.fhc.app.ble.BleNFCControl
import com.sychip.fhc.app.wsn.screen.WsnMapScreen
import com.sychip.fhc.AppCoverScreen
import kotlinx.coroutines.delay


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun StartTopAppBar(viewModel: StartViewModel) {

    val uiTestState by viewModel.testFlow.collectAsStateWithLifecycle()

    TopAppBar(
        title = {
            Text(text = APP.TITLE)
        },
        actions = {
//            IconButton(onClick = {
//                viewModel.onBabyCryUpdate(null)
//            }) {
//                Icon(Icons.Filled.Subtitles, null)
//            }
            if(APP.TYPE == AppType.Todo) {
                IconButton(onClick = {
                    viewModel.loadDialog()
                }) {
                    Icon(Icons.Filled.Subtitles, null)
                }

                IconButton(onClick = { viewModel.addPage() }) {
                    Icon(Icons.Filled.SubtitlesOff, null)
                }
            }else if(APP.TYPE == AppType.AcControl){
                val awsConnected by viewModel.awsConnected.collectAsStateWithLifecycle()
//                val rotateAngle = remember { Animatable(0f) }
//                LaunchedEffect(key1 = true) {
//                    rotateAngle.animateTo(targetValue = 360f, animationSpec = infiniteRepeatable(tween(600), RepeatMode.Restart))
//                }
                if(!awsConnected) {
                    val enable = uiTestState !is StartViewModel.UiTestState.Loading

                    IconButton(enabled = enable ,onClick = {
                        viewModel.reconnectAWS()
                    }) {
                        if(enable){
                            Icon(Icons.Filled.Refresh, contentDescription = null, tint = Color.White)
                        }else{
                            val infiniteTransition = rememberInfiniteTransition(label = "")
                            val rotateAngle by infiniteTransition.animateFloat(
                                initialValue = 0.0f,
                                targetValue = 360f,
                                animationSpec =  infiniteRepeatable(animation = tween(400, easing = LinearEasing)), label = ""
                            )
                            Icon(imageVector =  Icons.Filled.Refresh, modifier = Modifier.rotate(rotateAngle), contentDescription =  null, tint = Color.Gray)
                        }
                    }
                }
            }else if(APP.TYPE == AppType.WSN){
                IconButton(onClick = {
//                    wsnMapViewModel?.addDevice()
                }) {
                    Icon(Icons.Filled.Add, contentDescription = null, tint = Color.White)
                }

                IconButton(onClick = {
//                    wsnMapViewModel?.reloadDevices()
                }) {
                    Icon(Icons.Filled.Refresh, contentDescription = null, tint = Color.White)
                }
            }

//            if(viewModel != null){
//                val uiState by viewModel.uiState.collectAsStateWithLifecycle()
//                if (uiState.isTaskDeleted) {
//                    IconButton(onClick = {
////                        viewModel::deleteTask
//
//                    }) {
//                        Icon(Icons.Filled.AccountBox, null)
//                    }
//                }
//            }
        },
        modifier = Modifier.fillMaxWidth(),
//        backgroundColor = colorScheme.primary

        colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
            containerColor = colorScheme.primary,
            titleContentColor = Color.White,
        ),
    )
}


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun StartScreen(
    onGotoMainDrawer: () -> Unit,
    onGotoMainTab: () -> Unit,
    modifier: Modifier = Modifier,
    viewModel: StartViewModel = hiltViewModel(),
    nwViewModel: NetworkViewModel = hiltViewModel(),
    snackbarHostState: SnackbarHostState = remember { SnackbarHostState() }
) {

    //如果应用需要监控网络状态，请添加 APP.TYPE
    if( APP.TYPE == AppType.AcControl){
        val networkState by nwViewModel.networkState.collectAsStateWithLifecycle()
        if(networkState == ConnectionState.Unavailable){
            Box{
                Scaffold(
                    modifier = modifier.fillMaxSize(),
                    topBar = {
                        TopAppBar(
                            title = {
                                Text(text = APP.TITLE)
                            },
                            modifier = Modifier.fillMaxWidth(),
                            colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
                                containerColor = colorScheme.primary,
                                titleContentColor = Color.White,
                            ),
                        )
                    },
                ) { paddingValues ->
                    Box(modifier = Modifier.fillMaxSize().padding(paddingValues)) {
                        Box(modifier = Modifier.fillMaxSize().wrapContentSize().align(Alignment.Center)) {
                            Row{
                                Icon(Icons.Default.Warning, null, tint = Color.Red, modifier = Modifier.size(24.dp))

                                Text("   Network Error   ", fontSize = 20.sp, modifier = Modifier.wrapContentSize())
                            }
                        }
                    }
                }
            }
        }
    }else{

        //用来控制显示全局alert dialog
        val alertState by viewModel.alertState.collectAsStateWithLifecycle()

        if (alertState.showDialog) {
            AlertDialog(
                onDismissRequest = { viewModel.showDialog(false) },
                title = {
                            Row{
                                Icon(Icons.Filled.Info, modifier = Modifier.size(36.dp), tint = Color.Red, contentDescription =  stringResource(id = R.string.edit_task))
                                Text(alertState.title,color =Color.Black)
                            }
                        },
                text = { Text(alertState.text,color =Color.Black) },
                confirmButton = {
                    TextButton(onClick = {
                        viewModel.showDialog(false)
//                        onGotoMainTab()
                    }) {
                        Text("I Know".uppercase())
                    }
                }
            )
        }
        Box{
            Scaffold(
                snackbarHost = { SnackbarHost(snackbarHostState) },
                modifier = modifier.fillMaxSize(),
                topBar = {
                    StartTopAppBar(viewModel)
                },
                floatingActionButton = {
                    if (APP.TYPE == AppType.Todo){
                        Column {
                            FloatingActionButton(onClick = {
                                onGotoMainDrawer()
                            }) {
                                Icon(Icons.Filled.DragIndicator, stringResource(id = R.string.edit_task))
                            }
                            FloatingActionButton(
                                onClick = {
                                    onGotoMainTab()
                                }) {
                                Icon(Icons.Filled.Tab, stringResource(id = R.string.edit_task))
                            }
                        }
                    }
                }
            ) { paddingValues ->
                StartContent(
                    viewModel = viewModel,
                    modifier = Modifier.padding(paddingValues).fillMaxSize(),
                )
            }
            //启动画面，定时消失
            var showSplash by remember { mutableStateOf(true) }
            LaunchedEffect(null) {
                delay(3500)
                showSplash = false
            }
            if(showSplash) {
                AppCoverScreen()
            }
        }

    }


}

@Composable
private fun StartContent(
    viewModel: StartViewModel,
    modifier: Modifier = Modifier
) {
    if(APP.TYPE == AppType.AcControl){
        AcControl(viewModel)
    }else if(APP.TYPE == AppType.WSN){
        WsnMapScreen( )
    }else if(APP.TYPE == AppType.BleNFC){
        BleNFCControl(modifier)
    }else {
//        RequireBluetooth(
//            onChanged = { it ->
//                {
//                    Timber.i("RequireBluetooth   onChanged   >>>>>>$it")
//                }
//            },
//            contentWithoutBluetooth = { it ->
//                Timber.i("contentWithoutBluetooth      11111111111>>>>>>$it")
//                NoBluetoothView(it)
//            }
//        ) {
//            Timber.i("contentWithoutBluetooth      22222222222>>>>>>")
//            RequireLocation(
//                onChanged = { it ->
//                    {
//                        Timber.i("RequireLocation   onChanged   >>>>>>$it")
//                    }
//                },
//                contentWithoutLocation = {
//                }
//            ) { isLocationRequiredAndDisabled ->
//                if (isLocationRequiredAndDisabled) {
//                    NoBluetoothView(null)
//                } else {
//                    val appViewModel = MainApplication.instance().getAppViewModel()
//                    MainContent(appViewModel, onGotoMain, onGotoMainTab, modifier, viewModel, snackbarHostState)
//
//
////                    Timber.i("AICamera      00:80:E1:27:FD:4F  >>>>>>")
////                    appViewModel.connect("00:80:E1:27:FD:4F", "AICamera")
//
//                    //                val screenPadding = Modifier.padding(
//                    //                    horizontal = dimensionResource(id = R.dimen.horizontal_margin),
//                    //                    vertical = dimensionResource(id = R.dimen.vertical_margin),
//                    //                )
//                    //                val commonModifier = modifier.fillMaxWidth().then(screenPadding)
//                    //                Column(commonModifier.verticalScroll(rememberScrollState())) {
//                    //                    Aaa(viewModel, snackbarHostState)
//                    //                }
//                }
//            }
//        }
    }
}

